<template>
  <div class="p-2">

    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card" v-show="!dialog.visible">
          <div>
            <!-- <el-button v-if="!infoData.userName" type="primary" @click="handleAdd"
              >新增</el-button> -->
            <el-button type="primary" @click="handleUpdate(userList[0])">修改</el-button>
          </div>
          <div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                供应商名称
                <div class="pull-right">{{ infoData.supplierName }}</div>
              </li>
              <li class="list-group-item">
                登录账号
                <div class="pull-right">{{ infoData.userName }}</div>
              </li>
              <li class="list-group-item">
                邮箱地址
                <div class="pull-right">{{ infoData.email }}</div>
              </li>
              <li class="list-group-item">
                联系人
                <div class="pull-right">{{ infoData.contactName }}</div>
              </li>
              <li class="list-group-item">
                性别
                <div class="pull-right">{{ infoData.sex ? '男' : '女' }}</div>
              </li>
              <li class="list-group-item">
                联系电话
                <div class="pull-right">{{ infoData.phone }}</div>
              </li>
              <li class="list-group-item">
                微信
                <div class="pull-right">{{ infoData.wechat }}</div>
              </li>
              <li class="list-group-item">
                部门
                <div class="pull-right">{{ infoData.department }}</div>
              </li>
              <li class="list-group-item">
                职位
                <div class="pull-right">{{ infoData.position }}</div>
              </li>
              <li class="list-group-item">
                对接人
                <div class="pull-right">{{ infoData.counterpart }}</div>
              </li>
            </ul>
          </div>
        </el-card>
        <el-card v-show="dialog.visible">
          <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">

            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" clearable />
            </el-form-item>
            <el-form-item label="登录账号" prop="userName">
              <el-input disabled v-model="form.userName" placeholder="请输入用户账号" clearable />
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入用户邮箱" clearable />
            </el-form-item>
            <!-- <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item> -->
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" clearable />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" clearable>
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" clearable />
            </el-form-item>
            <el-form-item label="微信" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信" clearable />
            </el-form-item>
            <el-form-item label="部门" prop="department">
              <el-input v-model="form.department" placeholder="请输入部门" clearable />
            </el-form-item>
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" clearable />
            </el-form-item>
            <el-form-item label="对接人" prop="counterpart">
              <el-input v-model="form.counterpart" placeholder="请输入对接人" clearable />
            </el-form-item>

          </el-form>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24" style="display: none;">
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户ID" align="center" prop="userId" v-if="true" />
            <el-table-column label="部门ID" align="center" prop="deptId" />
            <el-table-column label="用户账号" align="center" prop="userName" />
            <el-table-column label="用户昵称" align="center" prop="nickName" />
            <el-table-column label="用户类型" align="center" prop="userType" />
            <el-table-column label="用户邮箱" align="center" prop="email" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="用户性别" align="center" prop="sex" />
            <el-table-column label="头像地址" align="center" prop="avatar" />
            <el-table-column label="密码" align="center" prop="password" />
            <el-table-column label="帐号状态" align="center" prop="status" />
            <el-table-column label="最后登录IP" align="center" prop="loginIp" />
            <el-table-column label="最后登录时间" align="center" prop="loginDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="供应商名称-----从这是新增的" align="center" prop="supplier" />
            <el-table-column label="联系人姓名" align="center" prop="contactName" />
            <el-table-column label="性别" align="center" prop="gender" />
            <el-table-column label="联系电话" align="center" prop="phone" />
            <el-table-column label="微信" align="center" prop="wechat" />
            <el-table-column label="部门" align="center" prop="department" />
            <el-table-column label="职位" align="center" prop="position" />
            <el-table-column label="对接人" align="center" prop="counterpart" />
            <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="User" lang="ts">
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/system/hmUser';
import { UserVO, UserQuery, UserForm } from '@/api/system/hmUser/types';
import { hmSupplierList, hmSupplierGet, hmSupplierPut } from '@/api/group/supplier/index'
import { SupplierTable } from '@/api/group/supplier/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { AddressInfoVO, AddressInfoQuery, AddressInfoForm } from '@/api/system/addressInfo/types';
import { validateSpaceAndEmoji } from '@/utils/validate'

const userList = ref<UserVO[]>([]);
// const userList = ref<UserVO[]>();
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const infoData: UserForm = reactive({})
const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  userType: undefined,
  email: undefined,
  phonenumber: undefined,
  sex: undefined,
  avatar: undefined,
  password: undefined,
  status: undefined,
  loginIp: undefined,
  loginDate: undefined,
  remark: undefined,
  supplier: undefined,
  contactName: undefined,
  gender: undefined,
  phone: undefined,
  wechat: undefined,
  department: undefined,
  position: undefined,
  counterpart: undefined,
  createdAt: undefined
}
const data = reactive<PageData<UserForm, UserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    userType: undefined,
    email: undefined,
    phonenumber: undefined,
    sex: undefined,
    avatar: undefined,
    password: undefined,
    status: undefined,
    loginIp: undefined,
    loginDate: undefined,
    supplier: undefined,
    contactName: undefined,
    gender: undefined,
    phone: undefined,
    wechat: undefined,
    department: undefined,
    position: undefined,
    counterpart: undefined,
    createdAt: undefined,
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    userType: [
      { required: true, message: "用户类型不能为空", trigger: "change" }
    ],
    email: [
      { required: true, message: "用户邮箱不能为空", trigger: "blur" }
    ],
    phonenumber: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    sex: [
      { required: true, message: "用户性别不能为空", trigger: "change" }, { validator: validateSpaceAndEmoji, }
    ],
    avatar: [
      { required: true, message: "头像地址不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    status: [
      { required: true, message: "帐号状态不能为空", trigger: "change" }
    ],
    loginIp: [
      { required: true, message: "最后登录IP不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    loginDate: [
      { required: true, message: "最后登录时间不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    supplier: [
      { required: true, message: "供应商名称不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    contactName: [
      { required: true, message: "联系人姓名不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    wechat: [
      { required: true, message: "微信不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    department: [
      { required: true, message: "部门不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    position: [
      { required: true, message: "职位不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    counterpart: [
      { required: true, message: "对接人不能为空", trigger: "blur" }, { validator: validateSpaceAndEmoji, }
    ],
    createdAt: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await hmSupplierList(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  Object.assign(infoData, res.rows[0])
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = "添加用户信息";
  nextTick(() => {
    reset();
  });
}

/** 修改按钮操作 */
const handleUpdate = (row?: UserVO) => {
  loading.value = true
  dialog.visible = true;
  dialog.title = "修改用户信息";
  nextTick(async () => {
    reset();
    const _userId = row?.userId || ids.value[0]
    const res = await hmSupplierGet(_userId);
    loading.value = false;
    Object.assign(form.value, res.data);
  });
}

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // if (form.value.userId) {
      //   await updateUser(form.value).finally(() => buttonLoading.value = false);
      // } else {
      //   await addUser(form.value).finally(() => buttonLoading.value = false);
      // }
      await hmSupplierPut((form.value) as any).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户信息编号为"' + _userIds + '"的数据项？').finally(() => loading.value = false);
  await delUser(_userIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/user/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-select) {
  width: 100% !important;
}
</style>
